//
//  MineViewController.swift
//  Story
//
//  Created by 汤泽川 on 2019/3/30.
//  Copyright © 2019 汤泽川. All rights reserved.
//

import UIKit
import RxSwift
import RxCocoa
import SnapKit

class MineViewController: UIViewController, UINavigationControllerDelegate, STFeedListViewDelegate {

    let avatarView = STAvatarView()
    let settingBtn = UIButton()
    let disposeBag = DisposeBag()
    let userData = BehaviorRelay<STUserDataModel>(value: STUserDataModel(follwoing: 0, follower: 0, collectCount: 0))
    let storyManager = STSearchAuthorListServiceManager(pageCount: 5)
    var feedListView : STFeedListView?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = UIColor(red: 244, green: 244, blue: 244, alpha: 1)
        buildView()
        setUpObserver()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        if STUserService.shareInstance.currentUser.value != nil {
            STUserService.shareInstance.fetchUserData().result { (model, error) in
                if model != nil {
                    self.userData.accept(model!)
                }
            }
        }
    }
    
    func buildView() {
        self.navigationController?.delegate = self
        self.view.addSubview(avatarView)
        avatarView.addTarget(self, action: #selector(didClickAvatarBtn), for: .touchUpInside)
        settingBtn.setImage(#imageLiteral(resourceName: "setting_icon"), for: .normal)
        settingBtn.setTitle("设置", for: .normal)
        settingBtn.setTitleColor(.gray, for: .normal)
        settingBtn.titleLabel?.font = UIFont.systemFont(ofSize: 14)
        settingBtn.addTarget(self, action: #selector(didClickSettingBtn), for: .touchUpInside)
        self.view.addSubview(settingBtn)
        
        let dataContent = UIView()
        dataContent.layer.cornerRadius = 4
        dataContent.layer.shadowColor = UIColor(white: 0, alpha: 0.3).cgColor
        dataContent.layer.shadowRadius = 2
        dataContent.layer.shadowOpacity = 1
        dataContent.layer.borderWidth = 0.5
        dataContent.layer.borderColor = UIColor(white: 0, alpha: 0.1).cgColor
        self.view.addSubview(dataContent)
        dataContent.snp.makeConstraints { (make) in
            make.left.right.equalToSuperview().inset(18)
            make.top.equalTo(avatarView.snp_bottom).offset(20)
            make.height.equalTo(60)
        }
        // 关注数
        let followingCount = STDetailItem(title: "关注数")
        followingCount.alphaBtn.rx.controlEvent(.touchUpInside).subscribe(onNext: {
            let followVC = STFollowListViewController()
            followVC.title = "我关注的"
            self.hidesBottomBarWhenPushed = true
            self.navigationController?.pushViewController(followVC, animated: true)
            self.hidesBottomBarWhenPushed = false
        }).disposed(by: disposeBag)
        self.view.addSubview(followingCount)
        followingCount.snp.makeConstraints { (make) in
            make.centerX.equalTo(dataContent).multipliedBy(0.5)
            make.centerY.equalTo(dataContent)
        }
        
        // 粉丝数
        let followerCount = STDetailItem(title: "粉丝数")
        followerCount.alphaBtn.rx.controlEvent(.touchUpInside).subscribe(onNext: {
            
        }).disposed(by: disposeBag)
        self.view.addSubview(followerCount)
        followerCount.snp.makeConstraints { (make) in
            make.centerX.equalTo(dataContent)
            make.centerY.equalTo(dataContent)
        }
        // 收藏数
        let collectCount = STDetailItem(title: "收藏数")
        collectCount.alphaBtn.rx.controlEvent(.touchUpInside).subscribe(onNext: {
            if STUserService.shareInstance.currentUser.value != nil {
                let collectVC = STUserStoryFeedViewController(storyManager: STCollectListServiceManager(pageCount: 20))
                collectVC.title = "我收藏的故事"
                self.hidesBottomBarWhenPushed = true
                self.navigationController?.pushViewController(collectVC, animated: true)
                self.hidesBottomBarWhenPushed = false
            }
        }).disposed(by: disposeBag)
        self.view.addSubview(collectCount)
        collectCount.snp.makeConstraints { (make) in
            make.centerX.equalTo(dataContent).multipliedBy(1.5)
            make.centerY.equalTo(dataContent)
        }
        
        userData.subscribe(onNext: { (model) in
            followerCount.countLabel.text = "\(model.follower)"
            followingCount.countLabel.text = "\(model.follwoing)"
            collectCount.countLabel.text = "\(model.collectCount)"
        }).disposed(by: disposeBag)
        // 我的文章
        let myArticleLabel = UILabel()
        myArticleLabel.text = "我的文章"
        myArticleLabel.textColor = .gray
        myArticleLabel.font = .systemFont(ofSize: 21)
        self.view.addSubview(myArticleLabel)
        myArticleLabel.snp.makeConstraints { (make) in
            make.top.equalTo(dataContent.snp_bottom).offset(20)
            make.left.equalToSuperview().offset(18)
            make.height.equalTo(22)
        }
        let myArticleLine = UIView()
        myArticleLine.backgroundColor = UIColor.init(white: 0, alpha: 0.1)
        self.view.addSubview(myArticleLine)
        myArticleLine.snp.makeConstraints { (make) in
            make.top.equalTo(myArticleLabel.snp_bottom).offset(5)
            make.left.right.equalToSuperview()
            make.height.equalTo(1)
        }
        feedListView = STFeedListView(serviceManager: storyManager)
        self.view.addSubview(feedListView!)
        feedListView?.listViewDelegate = self
        feedListView?.snp.makeConstraints({ (make) in
            make.top.equalTo(myArticleLine.snp_bottom).offset(5)
            make.left.right.equalToSuperview()
            make.bottom.equalToSuperview().offset(-self.view.safeAreaInsets.bottom - 44)
        })
    }
    
    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        settingBtn.snp.updateConstraints { (make) in
            make.top.equalToSuperview().offset(self.view.safeAreaInsets.top + 20)
            make.right.equalToSuperview().offset(-18)
            make.height.equalTo(25)
        }
        avatarView.snp.updateConstraints { (make) in
            make.width.equalToSuperview().offset(-36)
            make.centerX.equalToSuperview()
            make.top.equalTo(settingBtn.snp_bottom).offset(5)
        }
    }
    
    func setUpObserver() {
        STUserService.shareInstance.currentUser.subscribe(onNext: {[weak self] (userInfo) in
            self?.avatarView.update(user: userInfo)
            self?.storyManager.authorName = userInfo?.username
            self?.feedListView?.triggerRefreshing()
        }).disposed(by: disposeBag)
    }
    
    func navigationController(_ navigationController: UINavigationController, willShow viewController: UIViewController, animated: Bool) {
        navigationController.setNavigationBarHidden(viewController == self, animated: true)
    }
    
    @objc func didClickAvatarBtn() {
        if STUserService.shareInstance.currentUser.value == nil {
            let loginVC = STLoginViewController()
            self.hidesBottomBarWhenPushed = true
            self.present(loginVC, animated: true, completion: nil)
            self.hidesBottomBarWhenPushed = false
        } else {
            let profileVC = STUserInfoViewController()
            profileVC.title = "我的信息"
            self.hidesBottomBarWhenPushed = true
            self.navigationController?.pushViewController(profileVC, animated: true)
            self.hidesBottomBarWhenPushed = false
        }
    }
    
    @objc func didClickSettingBtn() {
        if STUserService.shareInstance.currentUser.value == nil {
            didClickAvatarBtn()
            return
        }
        let settingVC = STSettingViewController()
        settingVC.title = "设置"
        self.hidesBottomBarWhenPushed = true
        self.navigationController?.pushViewController(settingVC, animated: true)
        self.hidesBottomBarWhenPushed = false
    }
    func didClickCell(model: STStoryInfo) {
        let readVC = STReadStoryViewController(model: model)
        readVC.title = "Story"
        self.hidesBottomBarWhenPushed = true
        self.navigationController?.pushViewController(readVC, animated: true)
        self.hidesBottomBarWhenPushed = false
    }
    
}

class STDetailItem: UIView {
    let titleLabel = UILabel()
    let countLabel = UILabel()
    let alphaBtn = UIButton()
    
    init(title : String) {
        super.init(frame: CGRect.zero)
        
        countLabel.text = "0"
        countLabel.textColor = .gray
        countLabel.font = .systemFont(ofSize: 14)
        countLabel.textAlignment = .center
        self.addSubview(countLabel)
        countLabel.snp.makeConstraints { (make) in
            make.top.left.right.equalToSuperview()
            make.height.equalTo(16)
        }
        
        titleLabel.text = title
        titleLabel.textColor = .gray
        titleLabel.font = .systemFont(ofSize: 15)
        titleLabel.textAlignment = .center
        self.addSubview(titleLabel)
        titleLabel.snp.makeConstraints { (make) in
            make.top.equalTo(countLabel.snp_bottom).offset(5)
            make.left.right.bottom.equalToSuperview()
            make.height.equalTo(17)
        }
        self.addSubview(alphaBtn)
        alphaBtn.snp.makeConstraints { (make) in
            make.edges.equalToSuperview()
        }
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}
